import { nativeImage } from 'electron'
import sharp from 'sharp'

export interface WatermarkOptions {
  isDark?: boolean
  version?: string
  texts?: {
    brand?: string
    time?: string
    tip?: string
    model?: string // 模型名称
    provider?: string // 供应商名称
  }
}

/**
 * 创建水印SVG
 * @param width 图片宽度
 * @param options 水印选项
 */
const createWatermarkSvg = (width: number, options: WatermarkOptions): string => {
  const { isDark = false, version = '1.0.0', texts = {} } = options

  const borderHeight = 80
  const yPadding = 40
  const lineHeight = 24

  // 计算文本垂直居中的基准Y坐标
  const textBaselineY = borderHeight / 2 + 4
  const upperTextY = textBaselineY - lineHeight / 2 + 4
  const lowerTextY = textBaselineY + lineHeight / 2 + 4

  // 品牌标识和版本信息
  const brandText = texts.brand || 'AgentConnector'
  const versionInfo = 'v' + version

  // 构建时间信息，在时间戳前面添加模型和供应商信息
  const now = new Date()
  const timeStr =
    texts.time ||
    `${now.getFullYear()}/${String(now.getMonth() + 1).padStart(2, '0')}/${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`

  // 构建完整的时间行：模型信息 + 时间戳
  let timeLineText = ''
  if (texts.model || texts.provider) {
    const modelInfo: string[] = []
    if (texts.provider) {
      modelInfo.push(texts.provider)
    }
    if (texts.model) {
      modelInfo.push(texts.model)
    }
    timeLineText = `${modelInfo.join(' · ')} · ${timeStr}`
  } else {
    timeLineText = timeStr
  }

  const tipText = texts.tip || 'Generated by AgentConnector'

  const backgroundColor = isDark ? 'rgba(0, 0, 0, 0.8)' : 'rgba(255, 255, 255, 0.8)'
  const textColor = isDark ? 'rgba(255, 255, 255, 0.9)' : 'rgba(0, 0, 0, 0.9)'
  const lineColor = isDark ? 'rgba(200, 200, 200, 0.5)' : 'rgba(50, 50, 50, 0.5)'

  return `
    <svg width="${width}" height="${borderHeight}" xmlns="http://www.w3.org/2000/svg">
      <!-- 背景 -->
      <rect width="${width}" height="${borderHeight}" fill="${backgroundColor}"/>

      <!-- 分隔线 -->
      <rect x="0" y="0" width="${width}" height="1" fill="${lineColor}"/>

      <!-- 时间信息 (左对齐) -->
      <text x="${yPadding}" y="${upperTextY}" font-family="Arial, sans-serif" font-size="16" fill="${textColor}">
        ${timeLineText}
      </text>

      <!-- 提示文本 (左对齐) -->
      <text x="${yPadding}" y="${lowerTextY}" font-family="Arial, sans-serif" font-size="16" fill="${textColor}">
        ${tipText}
      </text>

      <!-- 品牌标识 (右对齐) -->
      <text x="${width - yPadding}" y="${upperTextY}" font-family="Arial, sans-serif" font-size="28" font-weight="bold" text-anchor="end" fill="${textColor}">
        ${brandText}
      </text>

      <!-- 版本信息 (右对齐) -->
      <text x="${width - yPadding}" y="${lowerTextY}" font-family="Arial, sans-serif" font-size="16" text-anchor="end" fill="${textColor}">
        ${versionInfo}
      </text>
    </svg>
  `
}

/**
 * 为图片添加水印 (主进程版本)
 * @param imageBuffer 原始图片的Buffer
 * @param options 水印选项
 */
export const addWatermarkToImage = async (
  imageBuffer: Buffer,
  options: WatermarkOptions = {}
): Promise<Buffer> => {
  try {
    // 获取原始图片信息
    const { width, height } = await sharp(imageBuffer).metadata()

    if (!width || !height) {
      throw new Error('无法获取图片尺寸')
    }

    const borderHeight = 80
    const watermarkSvg = createWatermarkSvg(width, options)
    const watermarkBuffer = Buffer.from(watermarkSvg)

    // 创建带水印的图片
    const result = await sharp({
      create: {
        width,
        height: height + borderHeight,
        channels: 4,
        background: { r: 0, g: 0, b: 0, alpha: 0 }
      }
    })
      .composite([
        // 原始图片
        {
          input: imageBuffer,
          top: 0,
          left: 0
        },
        // 水印
        {
          input: watermarkBuffer,
          top: height,
          left: 0
        }
      ])
      .png()
      .toBuffer()

    return result
  } catch (error) {
    console.error('添加水印时出错:', error)
    // 如果添加水印失败，返回原始图片
    return imageBuffer
  }
}

/**
 * 从nativeImage创建带水印的图片
 * @param image Electron nativeImage对象
 * @param options 水印选项
 */
export const addWatermarkToNativeImage = async (
  image: Electron.NativeImage,
  options: WatermarkOptions = {}
): Promise<Electron.NativeImage> => {
  const pngBuffer = image.toPNG()
  const watermarkedBuffer = await addWatermarkToImage(pngBuffer, options)
  return nativeImage.createFromBuffer(watermarkedBuffer)
}
